package autocode;

import com.celesea.auth.core.util.StringKit;
import com.celesea.auth.menu.dao.MenuDao;
import com.celesea.auth.menu.entity.Menu;
import com.google.common.collect.Lists;

import javax.persistence.Column;
import javax.persistence.Table;
import java.lang.reflect.Field;
import java.util.List;

public class MapperBatchInputUtil {


	public static void main(String[] args) {
		renderMap(MenuDao.class, Menu.class);
	}

	public static void renderMap(Class<?> dao, Class<?> clazz) {
		renderMap(dao.getName(), clazz);
	}

	public static void renderMap(String dao, Class<?> clazz) {
		Table table = clazz.getAnnotation(Table.class);
		String name = clazz.getName();
		if (StringKit.isEmpty(dao)) {
			dao = name.replace("entity", "dao") + "Dao";
		}

		List<Field> fields = Lists.newArrayList(clazz.getDeclaredFields());
		clazz = clazz.getSuperclass();
		fields.addAll(0, Lists.newArrayList(clazz.getDeclaredFields()));
		clazz = clazz.getSuperclass();
		fields.addAll(0, Lists.newArrayList(clazz.getDeclaredFields()));

		StringBuffer buffer = new StringBuffer();
		StringBuffer selectBuffer = new StringBuffer();
		boolean first = true;
		for (Field field : fields) {
			Column column = field.getAnnotation(Column.class);
			if (column != null) {
				if (first) {
					first = false;
					buffer.append(sqlFlag(column.name()));
					selectBuffer.append("#{item." + field.getName() + "}");
				} else {
					buffer.append(",").append(sqlFlag(column.name()));
					selectBuffer.append(",").append("#{item." + field.getName() + "}");
				}
			}
		}

		System.out.println("<!-- 批量插入 -->");
		System.out.println("<insert id=\"insertBatch\" parameterType=\"java.util.List\">");
		System.out.println("<![CDATA[");
		System.out.println(" insert into " + table.name() + "(" + buffer + ")");
		System.out.println(" values ");
		System.out.println("]]>");
		System.out.println("<foreach collection=\"list\" item=\"item\" index=\"index\" separator=\",\">");
		System.out.println("(" + selectBuffer + ")");
		System.out.println("</foreach>");
		System.out.println("</insert>");

	}

	private static String sqlFlag(String column) {
		if (!column.startsWith("`")) {
			column = "`" + column;
		}
		if (!column.endsWith("`")) {
			column = column + "`";
		}
		return column;
	}

}
